use async_trait::async_trait;
use indicatif::{ProgressBar, ProgressStyle, MultiProgress};
use std::sync::Arc;
use std::collections::HashMap;
use tokio::sync::RwLock;

/// 分片下载状态
#[derive(Debug, Clone, PartialEq)]
pub enum SegmentStatus {
    Connecting,  // 新增：正在连接状态
    Downloading,
    Success,
    Error,
    Retrying,
}

/// 双层进度报告接口
#[async_trait]
pub trait DualProgressReporter: Send + Sync {
    /// 设置当前正在下载的m3u8信息（固定显示）
    async fn set_current_download(&self, url: &str, message: &str);
    
    /// 开始总进度跟踪
    async fn start_total_progress(&self, total: u64, message: &str);
    
    /// 更新总进度
    async fn increment_total(&self, delta: u64);
    
    /// 设置总进度消息
    async fn set_total_message(&self, message: &str);
    
    /// 完成总进度
    async fn finish_total(&self, message: &str);
    
    /// 开始TS分片下载进度
    async fn start_segment_progress(&self, segment_id: usize, segment_url: &str, progress_icon: &str);
    
    /// 更新TS分片进度
    async fn update_segment_progress(&self, segment_id: usize, downloaded: u64, total: u64);
    
    /// 设置TS分片状态（成功/错误/重试）
    async fn set_segment_status(&self, segment_id: usize, status: SegmentStatus, message: &str, progress_icon: &str);
    
    /// 完成TS分片下载（成功时移除进度条）
    async fn finish_segment(&self, segment_id: usize, success: bool);
    
    /// 克隆进度报告器
    fn clone_reporter(&self) -> Box<dyn DualProgressReporter>;
}

/// 只显示总进度条的进度报告器
pub struct TotalOnlyProgressReporter {
    multi_progress: Arc<MultiProgress>,
    current_download: Arc<RwLock<Option<ProgressBar>>>, // 当前下载状态行
    total_progress: Arc<RwLock<Option<ProgressBar>>>,
    // 不存储分片进度条，只保留HashMap以满足接口要求
    _segment_progress_bars: Arc<RwLock<HashMap<usize, ProgressBar>>>,
}

impl TotalOnlyProgressReporter {
    pub fn new() -> Self {
        Self {
            multi_progress: Arc::new(MultiProgress::new()),
            current_download: Arc::new(RwLock::new(None)),
            total_progress: Arc::new(RwLock::new(None)),
            _segment_progress_bars: Arc::new(RwLock::new(HashMap::new())),
        }
    }
    
    fn create_total_progress_style() -> ProgressStyle {
        ProgressStyle::default_bar()
            .template("🎯 总进度: [{bar:50.green/red}] {pos:>3}/{len:3} ({percent:>3}%) {msg}")
            .unwrap()
            .progress_chars("█▉▊▋▌▍▎▏ ")
    }
    
    fn create_current_download_style() -> ProgressStyle {
        ProgressStyle::default_bar()
            .template("📥 正在下载: {msg}")
            .unwrap()
    }
}

impl Default for TotalOnlyProgressReporter {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DualProgressReporter for TotalOnlyProgressReporter {
    async fn set_current_download(&self, url: &str, message: &str) {
        let pb = self.multi_progress.add(ProgressBar::new_spinner());
        pb.set_style(Self::create_current_download_style());
        pb.set_message(format!("{url} ({message})"));
        pb.enable_steady_tick(std::time::Duration::from_millis(100));
        
        let mut guard = self.current_download.write().await;
        *guard = Some(pb);
    }
    
    async fn start_total_progress(&self, total: u64, message: &str) {
        let pb = self.multi_progress.add(ProgressBar::new(total));
        pb.set_style(Self::create_total_progress_style());
        pb.set_message(message.to_string());
        
        let mut guard = self.total_progress.write().await;
        *guard = Some(pb);
    }
    
    async fn increment_total(&self, delta: u64) {
        let guard = self.total_progress.read().await;
        if let Some(ref pb) = *guard {
            pb.inc(delta);
        }
    }
    
    async fn set_total_message(&self, message: &str) {
        let guard = self.total_progress.read().await;
        if let Some(ref pb) = *guard {
            pb.set_message(message.to_string());
        }
    }
    
    async fn finish_total(&self, message: &str) {
        let guard = self.total_progress.read().await;
        if let Some(ref pb) = *guard {
            pb.finish_with_message(message.to_string());
        }
    }
    
    async fn start_segment_progress(&self, _segment_id: usize, _segment_url: &str, _progress_icon: &str) {
        // 不显示分片进度条
    }
    
    async fn update_segment_progress(&self, _segment_id: usize, _downloaded: u64, _total: u64) {
        // 不更新分片进度条
    }
    
    async fn set_segment_status(&self, _segment_id: usize, _status: SegmentStatus, _message: &str, _progress_icon: &str) {
        // 不更新分片状态
    }
    
    async fn finish_segment(&self, _segment_id: usize, _success: bool) {
        // 不处理分片完成状态
    }
    
    fn clone_reporter(&self) -> Box<dyn DualProgressReporter> {
        Box::new(TotalOnlyProgressReporter {
            multi_progress: Arc::clone(&self.multi_progress),
            current_download: Arc::clone(&self.current_download),
            total_progress: Arc::clone(&self.total_progress),
            _segment_progress_bars: Arc::clone(&self._segment_progress_bars),
        })
    }
}

/// 进度报告接口（保持向后兼容）
#[async_trait]
pub trait ProgressReporter: Send + Sync {
    /// 开始新的进度跟踪
    async fn start(&self, total: u64, message: &str);
    
    /// 增加进度
    async fn increment(&self, delta: u64);
    
    /// 设置当前进度
    async fn set_position(&self, position: u64);
    
    /// 更新消息
    async fn set_message(&self, message: &str);
    
    /// 完成进度
    async fn finish(&self, message: &str);
    
    /// 克隆进度报告器
    fn clone_reporter(&self) -> Box<dyn ProgressReporter>;
}

/// 双层控制台进度条实现
pub struct DualConsoleProgressReporter {
    multi_progress: Arc<MultiProgress>,
    current_download: Arc<RwLock<Option<ProgressBar>>>, // 当前下载状态行
    total_progress: Arc<RwLock<Option<ProgressBar>>>,
    segment_progress_bars: Arc<RwLock<HashMap<usize, ProgressBar>>>,
}

impl DualConsoleProgressReporter {
    pub fn new() -> Self {
        Self {
            multi_progress: Arc::new(MultiProgress::new()),
            current_download: Arc::new(RwLock::new(None)),
            total_progress: Arc::new(RwLock::new(None)),
            segment_progress_bars: Arc::new(RwLock::new(HashMap::new())),
        }
    }
    
    fn create_total_progress_style() -> ProgressStyle {
        ProgressStyle::default_bar()
            .template("🎯 总进度: [{bar:50.green/red}] {pos:>3}/{len:3} ({percent:>3}%) {msg}")
            .unwrap()
            .progress_chars("█▉▊▋▌▍▎▏ ")
    }
    
    fn create_current_download_style() -> ProgressStyle {
        ProgressStyle::default_bar()
            .template("📥 正在下载: {msg}")
            .unwrap()
    }
    
    fn create_segment_progress_style(status: &SegmentStatus, progress_icon: &str) -> ProgressStyle {
        match status {
            SegmentStatus::Connecting => {
                ProgressStyle::default_bar()
                    .template(&format!("  🔗 {progress_icon} [──────────────────────────────] 连接中... {{}}"))
                    .unwrap()
            }
            SegmentStatus::Downloading => {
                ProgressStyle::default_bar()
                    .template(&format!("  {progress_icon} [{{bar:30.cyan/blue}}] {{bytes}}/{{total_bytes}} {{msg}}"))
                    .unwrap()
                    .progress_chars("█▉▊▋▌▍▎▏ ")
            }
            SegmentStatus::Success => {
                ProgressStyle::default_bar()
                    .template(&format!("  ✅ {progress_icon} [{{bar:30.green}}] {{bytes}}/{{total_bytes}} {{msg}}"))
                    .unwrap()
                    .progress_chars("██")
            }
            SegmentStatus::Error => {
                ProgressStyle::default_bar()
                    .template(&format!("  ❌ {progress_icon} [{{bar:30.red}}] {{bytes}}/{{total_bytes}} {{msg}}"))
                    .unwrap()
                    .progress_chars("██")
            }
            SegmentStatus::Retrying => {
                ProgressStyle::default_bar()
                    .template(&format!("  🔄 {progress_icon} [{{bar:30.yellow/red}}] {{bytes}}/{{total_bytes}} {{msg}}"))
                    .unwrap()
                    .progress_chars("█▉▊▋▌▍▎▏ ")
            }
        }
    }
}

impl Default for DualConsoleProgressReporter {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DualProgressReporter for DualConsoleProgressReporter {
    async fn set_current_download(&self, url: &str, message: &str) {
        let pb = self.multi_progress.add(ProgressBar::new_spinner());
        pb.set_style(Self::create_current_download_style());
        pb.set_message(format!("{url} ({message})"));
        pb.enable_steady_tick(std::time::Duration::from_millis(100));
        
        let mut guard = self.current_download.write().await;
        *guard = Some(pb);
    }
    
    async fn start_total_progress(&self, total: u64, message: &str) {
        let pb = self.multi_progress.add(ProgressBar::new(total));
        pb.set_style(Self::create_total_progress_style());
        pb.set_message(message.to_string());
        
        let mut guard = self.total_progress.write().await;
        *guard = Some(pb);
    }
    
    async fn increment_total(&self, delta: u64) {
        let guard = self.total_progress.read().await;
        if let Some(ref pb) = *guard {
            pb.inc(delta);
        }
    }
    
    async fn set_total_message(&self, message: &str) {
        let guard = self.total_progress.read().await;
        if let Some(ref pb) = *guard {
            pb.set_message(message.to_string());
        }
    }
    
    async fn finish_total(&self, message: &str) {
        let guard = self.total_progress.read().await;
        if let Some(ref pb) = *guard {
            pb.finish_with_message(message.to_string());
        }
    }
    
    async fn start_segment_progress(&self, segment_id: usize, segment_url: &str, progress_icon: &str) {
        let pb = self.multi_progress.add(ProgressBar::new(0)); // 初始大小为0，稍后设置
        pb.set_style(Self::create_segment_progress_style(&SegmentStatus::Downloading, progress_icon));
        pb.set_message(format!("下载中: {}", 
            segment_url.chars().rev().take(30).collect::<String>().chars().rev().collect::<String>()));
        
        let mut guard = self.segment_progress_bars.write().await;
        guard.insert(segment_id, pb);
    }
    
    async fn update_segment_progress(&self, segment_id: usize, downloaded: u64, total: u64) {
        let guard = self.segment_progress_bars.read().await;
        if let Some(pb) = guard.get(&segment_id) {
            if pb.length() != Some(total) {
                pb.set_length(total);
            }
            pb.set_position(downloaded);
        }
    }
    
    async fn set_segment_status(&self, segment_id: usize, status: SegmentStatus, message: &str, progress_icon: &str) {
        let guard = self.segment_progress_bars.read().await;
        if let Some(pb) = guard.get(&segment_id) {
            pb.set_style(Self::create_segment_progress_style(&status, progress_icon));
            pb.set_message(message.to_string());
        }
    }
    
    async fn finish_segment(&self, segment_id: usize, success: bool) {
        let mut guard = self.segment_progress_bars.write().await;
        if let Some(pb) = guard.remove(&segment_id) {
            if success {
                // 成功时短暂显示成功状态后清除
                pb.finish_with_message("✅ 下载完成".to_string());
                // 使用异步任务在短暂延迟后清除成功的进度条
                let pb_clone = pb.clone();
                tokio::spawn(async move {
                    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
                    pb_clone.finish_and_clear();
                });
            } else {
                // 失败时保持显示错误状态
                pb.finish_with_message("❌ 下载失败".to_string());
            }
        }
    }
    
    fn clone_reporter(&self) -> Box<dyn DualProgressReporter> {
        Box::new(DualConsoleProgressReporter {
            multi_progress: Arc::clone(&self.multi_progress),
            current_download: Arc::clone(&self.current_download),
            total_progress: Arc::clone(&self.total_progress),
            segment_progress_bars: Arc::clone(&self.segment_progress_bars),
        })
    }
}

/// 控制台进度条实现（单层，向后兼容）
pub struct ConsoleProgressReporter {
    progress_bar: Arc<RwLock<Option<ProgressBar>>>,
}

impl ConsoleProgressReporter {
    pub fn new() -> Self {
        Self {
            progress_bar: Arc::new(RwLock::new(None)),
        }
    }
}

impl Default for ConsoleProgressReporter {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ProgressReporter for ConsoleProgressReporter {
    async fn start(&self, total: u64, message: &str) {
        let pb = ProgressBar::new(total);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos:>3}/{len:3} ({percent:>3}%) {msg}")
                .unwrap()
                .progress_chars("█▉▊▋▌▍▎▏ ")
        );
        pb.set_message(message.to_string());
        
        let mut guard = self.progress_bar.write().await;
        *guard = Some(pb);
    }

    async fn increment(&self, delta: u64) {
        let guard = self.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            pb.inc(delta);
        }
    }

    async fn set_position(&self, position: u64) {
        let guard = self.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            pb.set_position(position);
        }
    }

    async fn set_message(&self, message: &str) {
        let guard = self.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            pb.set_message(message.to_string());
        }
    }

    async fn finish(&self, message: &str) {
        let guard = self.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            pb.finish_with_message(message.to_string());
        }
    }

    fn clone_reporter(&self) -> Box<dyn ProgressReporter> {
        Box::new(ConsoleProgressReporter {
            progress_bar: Arc::clone(&self.progress_bar),
        })
    }
}

/// 静默进度报告器（用于测试或不需要显示进度的场景）
pub struct SilentProgressReporter;

#[async_trait]
impl ProgressReporter for SilentProgressReporter {
    async fn start(&self, _total: u64, _message: &str) {}
    async fn increment(&self, _delta: u64) {}
    async fn set_position(&self, _position: u64) {}
    async fn set_message(&self, _message: &str) {}
    async fn finish(&self, _message: &str) {}
    
    fn clone_reporter(&self) -> Box<dyn ProgressReporter> {
        Box::new(SilentProgressReporter)
    }
}

/// 静默双层进度报告器（用于测试）
pub struct SilentDualProgressReporter;

#[async_trait]
impl DualProgressReporter for SilentDualProgressReporter {
    async fn set_current_download(&self, _url: &str, _message: &str) {}
    async fn start_total_progress(&self, _total: u64, _message: &str) {}
    async fn increment_total(&self, _delta: u64) {}
    async fn set_total_message(&self, _message: &str) {}
    async fn finish_total(&self, _message: &str) {}
    async fn start_segment_progress(&self, _segment_id: usize, _segment_url: &str, _progress_icon: &str) {}
    async fn update_segment_progress(&self, _segment_id: usize, _downloaded: u64, _total: u64) {}
    async fn set_segment_status(&self, _segment_id: usize, _status: SegmentStatus, _message: &str, _progress_icon: &str) {}
    async fn finish_segment(&self, _segment_id: usize, _success: bool) {}
    
    fn clone_reporter(&self) -> Box<dyn DualProgressReporter> {
        Box::new(SilentDualProgressReporter)
    }
}

/// 进度报告器工厂
pub struct ProgressReporterFactory;

impl ProgressReporterFactory {
    pub fn create_console_reporter() -> Box<dyn ProgressReporter> {
        Box::new(ConsoleProgressReporter::new())
    }
    
    pub fn create_silent_reporter() -> Box<dyn ProgressReporter> {
        Box::new(SilentProgressReporter)
    }
    
    pub fn create_dual_console_reporter() -> Box<dyn DualProgressReporter> {
        Box::new(DualConsoleProgressReporter::new())
    }
    
    pub fn create_silent_dual_reporter() -> Box<dyn DualProgressReporter> {
        Box::new(SilentDualProgressReporter)
    }
    
    /// 创建只显示总进度条的报告器
    pub fn create_total_only_reporter() -> Box<dyn DualProgressReporter> {
        Box::new(TotalOnlyProgressReporter::new())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::{timeout, Duration};

    #[tokio::test]
    async fn test_console_progress_reporter_new() {
        let reporter = ConsoleProgressReporter::new();
        let guard = reporter.progress_bar.read().await;
        assert!(guard.is_none());
    }

    #[tokio::test]
    async fn test_console_progress_reporter_default() {
        let reporter = ConsoleProgressReporter::default();
        let guard = reporter.progress_bar.read().await;
        assert!(guard.is_none());
    }

    #[tokio::test]
    async fn test_console_progress_reporter_start() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "测试进度").await;
        
        let guard = reporter.progress_bar.read().await;
        assert!(guard.is_some());
        
        if let Some(ref pb) = *guard {
            assert_eq!(pb.length(), Some(100));
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_increment() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "测试进度").await;
        reporter.increment(10).await;
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), 10);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_increment_multiple() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "测试进度").await;
        reporter.increment(5).await;
        reporter.increment(15).await;
        reporter.increment(20).await;
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), 40);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_set_position() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "测试进度").await;
        reporter.set_position(50).await;
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), 50);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_set_position_multiple() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "测试进度").await;
        reporter.set_position(25).await;
        reporter.set_position(75).await;
        reporter.set_position(10).await; // 测试向后设置
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), 10);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_set_message() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "初始消息").await;
        reporter.set_message("新消息").await;
        
        // 由于 indicatif 没有直接的方法获取消息，我们只能测试不会panic
        // 实际消息的验证在集成测试中进行
        let guard = reporter.progress_bar.read().await;
        assert!(guard.is_some());
    }

    #[tokio::test]
    async fn test_console_progress_reporter_finish() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "测试进度").await;
        reporter.increment(50).await;
        reporter.finish("完成").await;
        
        // 测试finish后进度条仍然存在（只是完成状态）
        let guard = reporter.progress_bar.read().await;
        assert!(guard.is_some());
    }

    #[tokio::test]
    async fn test_console_progress_reporter_clone_reporter() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(100, "测试进度").await;
        reporter.increment(30).await;
        
        let cloned = reporter.clone_reporter();
        
        // 测试克隆的报告器可以继续操作
        cloned.increment(20).await;
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), 50);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_concurrent_operations() {
        let reporter = Arc::new(ConsoleProgressReporter::new());
        
        reporter.start(1000, "并发测试").await;
        
        let mut handles = Vec::new();
        
        // 创建多个并发任务
        for i in 0..10 {
            let reporter_clone = Arc::clone(&reporter);
            let handle = tokio::spawn(async move {
                for _ in 0..10 {
                    reporter_clone.increment(1).await;
                    if i % 2 == 0 {
                        reporter_clone.set_message(&format!("任务 {i} 运行中")).await;
                    }
                }
            });
            handles.push(handle);
        }
        
        // 等待所有任务完成
        for handle in handles {
            handle.await.unwrap();
        }
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), 100);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_operations_without_start() {
        let reporter = ConsoleProgressReporter::new();
        
        // 测试在没有调用 start 的情况下操作不会panic
        reporter.increment(10).await;
        reporter.set_position(50).await;
        reporter.set_message("消息").await;
        reporter.finish("完成").await;
        
        let guard = reporter.progress_bar.read().await;
        assert!(guard.is_none());
    }

    #[tokio::test]
    async fn test_console_progress_reporter_extreme_values() {
        let reporter = ConsoleProgressReporter::new();
        
        // 测试极值
        reporter.start(u64::MAX, "极大值测试").await;
        reporter.increment(1000000).await;
        reporter.set_position(u64::MAX - 1).await;
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), u64::MAX - 1);
        }
    }

    #[tokio::test]
    async fn test_silent_progress_reporter_all_operations() {
        let reporter = SilentProgressReporter;
        
        // 测试所有操作都不会panic且快速完成
        let start_time = std::time::Instant::now();
        
        reporter.start(100, "测试").await;
        reporter.increment(10).await;
        reporter.set_position(50).await;
        reporter.set_message("消息").await;
        reporter.finish("完成").await;
        
        let elapsed = start_time.elapsed();
        assert!(elapsed < Duration::from_millis(10)); // 应该非常快
    }

    #[tokio::test]
    async fn test_silent_progress_reporter_clone() {
        let reporter = SilentProgressReporter;
        let cloned = reporter.clone_reporter();
        
        // 测试克隆的报告器也能正常工作
        cloned.start(100, "测试").await;
        cloned.increment(50).await;
        cloned.finish("完成").await;
    }

    #[tokio::test]
    async fn test_silent_progress_reporter_concurrent() {
        let reporter = Arc::new(SilentProgressReporter);
        
        let mut handles = Vec::new();
        
        // 创建大量并发任务测试性能
        for _ in 0..100 {
            let reporter_clone = Arc::clone(&reporter);
            let handle = tokio::spawn(async move {
                reporter_clone.start(1000, "并发测试").await;
                for _ in 0..100 {
                    reporter_clone.increment(1).await;
                }
                reporter_clone.finish("完成").await;
            });
            handles.push(handle);
        }
        
        let start_time = std::time::Instant::now();
        
        // 等待所有任务完成
        for handle in handles {
            handle.await.unwrap();
        }
        
        let elapsed = start_time.elapsed();
        assert!(elapsed < Duration::from_millis(100)); // 应该很快完成
    }

    #[test]
    fn test_progress_reporter_factory_console() {
        let reporter = ProgressReporterFactory::create_console_reporter();
        
        // 使用 Any trait 检查类型
        let any_reporter = &reporter as &dyn std::any::Any;
        assert!(any_reporter.is::<Box<dyn ProgressReporter>>());
    }

    #[test]
    fn test_progress_reporter_factory_silent() {
        let reporter = ProgressReporterFactory::create_silent_reporter();
        
        // 使用 Any trait 检查类型
        let any_reporter = &reporter as &dyn std::any::Any;
        assert!(any_reporter.is::<Box<dyn ProgressReporter>>());
    }

    #[tokio::test]
    async fn test_progress_reporter_factory_different_types() {
        let console_reporter = ProgressReporterFactory::create_console_reporter();
        let silent_reporter = ProgressReporterFactory::create_silent_reporter();
        
        // 测试两种类型的报告器都能正常工作
        console_reporter.start(100, "控制台测试").await;
        silent_reporter.start(100, "静默测试").await;
        
        console_reporter.increment(50).await;
        silent_reporter.increment(50).await;
        
        console_reporter.finish("控制台完成").await;
        silent_reporter.finish("静默完成").await;
    }

    #[tokio::test]
    async fn test_console_progress_reporter_rapid_updates() {
        let reporter = ConsoleProgressReporter::new();
        
        reporter.start(1000, "快速更新测试").await;
        
        // 快速连续更新
        for i in 0..100 {
            reporter.increment(1).await;
            if i % 10 == 0 {
                reporter.set_message(&format!("进度: {i}")).await;
            }
        }
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.position(), 100);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_restart() {
        let reporter = ConsoleProgressReporter::new();
        
        // 第一次使用
        reporter.start(100, "第一次").await;
        reporter.increment(50).await;
        reporter.finish("第一次完成").await;
        
        // 重新开始
        reporter.start(200, "第二次").await;
        reporter.increment(100).await;
        
        let guard = reporter.progress_bar.read().await;
        if let Some(ref pb) = *guard {
            assert_eq!(pb.length(), Some(200));
            assert_eq!(pb.position(), 100);
        }
    }

    #[tokio::test]
    async fn test_console_progress_reporter_timeout_safety() {
        let reporter = ConsoleProgressReporter::new();
        
        // 测试操作不会无限阻塞
        let result = timeout(Duration::from_secs(1), async {
            reporter.start(100, "超时测试").await;
            for _ in 0..50 {
                reporter.increment(1).await;
            }
            reporter.finish("完成").await;
        }).await;
        
        assert!(result.is_ok());
    }
}